package com.codename1.samples;


import com.codename1.components.Accordion;
import static com.codename1.ui.CN.*;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.Label;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.ui.Toolbar;
import java.io.IOException;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.io.NetworkEvent;
import com.codename1.ui.CN;
import com.codename1.ui.CheckBox;
import com.codename1.ui.Component;
import static com.codename1.ui.Component.RIGHT;
import static com.codename1.ui.ComponentSelector.$;
import com.codename1.ui.Container;
import com.codename1.ui.Font;
import com.codename1.ui.FontImage;
import com.codename1.ui.layouts.FlowLayout;
import com.codename1.ui.plaf.Border;
import com.codename1.ui.plaf.Style;

/**
 * This file was generated by <a href="https://www.codenameone.com/">Codename One</a> for the purpose 
 * of building native mobile applications using Java.
 */
public class AccordionSample {

    private Form current;
    private Resources theme;

    public void init(Object context) {
        UIManager.getInstance().getLookAndFeel().setRTL(true);
        // use two network threads instead of one
        updateNetworkThreadCount(2);

        theme = UIManager.initFirstTheme("/theme");

        // Enable Toolbar on all Forms by default
        Toolbar.setGlobalToolbar(true);

        // Pro only feature
        Log.bindCrashProtection(true);

        addNetworkErrorListener(err -> {
            // prevent the event from propagating
            err.consume();
            if(err.getError() != null) {
                Log.e(err.getError());
            }
            Log.sendLogAsync();
            Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
        });        
    }
    
    public void start() {
        if(current != null){
            current.show();
            return;
        }
        new TheForm().show();
    }
    
    /**
     * A sample of how to customize the style of the Accordion open/close arrows.  In this case
     * we are adjusting the padding at runtime so that the arrow is aligned with the edge of the
     * longest header label, but with a small amount of padding.
     * @param acc 
     */
    private void setupOpenCloseArrowStyles(Accordion acc) {
        // Load the OpenCloseIconUIID Style.  This is the UIID that is used to style the open/close arrows
        // of the Accordion component.
        Style openCloseIconStyle = UIManager.getInstance().getComponentStyle(acc.getOpenCloseIconUIID());
        
        // Set the margin to use pixels.
        openCloseIconStyle.setMarginUnit(Style.UNIT_TYPE_PIXELS, Style.UNIT_TYPE_PIXELS, Style.UNIT_TYPE_PIXELS, Style.UNIT_TYPE_PIXELS);

        // Now figure out how wide the accordion labels are going to be.  
        String[] labels = new String[]{"Section 1", "Section 2", "Section 3 (Custom)"};
        int maxLabelWidth = 0;
        for (String label : labels) {
            Font font = UIManager.getInstance().getComponentStyle(acc.getHeaderUIID()).getFont();
            maxLabelWidth = Math.max(maxLabelWidth, font.stringWidth(label));
            
        }
        System.out.println("MaxLabelWidth = "+maxLabelWidth);

        // Set the "Rigth" padding to be the screen width, less our label widths, and some constant padding.
        int rightPadding = CN.getDisplayWidth() - maxLabelWidth - CN.convertToPixels(25);
        System.out.println("Padding: "+rightPadding);
        openCloseIconStyle.setPadding(RIGHT, rightPadding);
        openCloseIconStyle.setFgColor(0x0);
        
        String customUIID = "PaddedOpenCloseIcon"+(CN.isPortrait()?"Portrait":"Landscape");
        String oldCustomUIID = "PaddedOpenCloseIcon"+(CN.isPortrait()?"Landscape":"Portrait");
        
        // Now we install our modified style into the UIManager so that it can be referenced by UIID.
        UIManager.getInstance().setComponentStyle(customUIID, openCloseIconStyle);
        
        // Now specify that the Accordion should use this newly installed UIID for the open/close arrows.
        acc.setOpenCloseIconUIID(customUIID);
        
        
        // In the case of screen orientation changes, we will need to update the old UIIDs to the new UIID.
        $(oldCustomUIID, acc).setUIID(customUIID);
        if (acc.getComponentForm() != null) {
            acc.revalidateWithAnimationSafety();
        }
    }
    
    class TheForm extends Form {
        TheForm() {
            super("Hi world", BoxLayout.y());
            Font arialbd = Font.createTrueTypeFont("arialbd", "arialbd.ttf").derive(Display.getInstance().convertToPixels(4), Font.STYLE_PLAIN);
            Form hi = this;
            Accordion acc = new Accordion();
            
            acc.setScrollableY(false);
            
            // Set up the styles for the open/close arrows of the UIID
            setupOpenCloseArrowStyles(acc);
            
            // Add orientation listener to update the open/close arrow styles to adjust to new screen sizes.
            hi.addOrientationListener(e->{
                setupOpenCloseArrowStyles(acc);
            });
            hi.addSizeChangedListener(e->{
                setupOpenCloseArrowStyles(acc);
            });
            acc.addContent("Section 1", new Label("Section 1 content"));
            acc.addContent("Section 2", new Label("Section 2 content"));
            acc.addContent("Section 3 (Custom)", new Label("Section 3 content"));
            hi.add(acc);
            CheckBox rtl = new CheckBox("RTL");
            rtl.setSelected(isRTL());
            hebrew = isRTL();
            rtl.addActionListener(e-> {
                getUIManager().getLookAndFeel().setRTL(rtl.isSelected());
                hebrew = rtl.isSelected();
                //getUIManager().getLookAndFeel().refreshTheme(true);
                new TheForm().show();
                //hi.refreshTheme();
            });
            CheckBox tooLong = new CheckBox("Too Long to fit on one line.  Lorem Ipsum, hello world, fooobarlllll  hello again");
            CheckBox alignRight = new CheckBox("Align Right Too Long to fit on one line.  Lorem Ipsum, hello world, fooobarlllll  hello again");
            $(alignRight).selectAllStyles().setAlignment(RIGHT);

            hi.add(rtl);
            hi.add(tooLong);
            hi.add(alignRight);
            
            CheckBox sameSide = new CheckBox("Same Side");
            sameSide.setOppositeSide(false);
            hi.add(sameSide);
            
            CheckBox sameSideAlignRight = new CheckBox("Same Side Right");
            sameSideAlignRight.setOppositeSide(false);
            $(sameSideAlignRight).selectAllStyles().setAlignment(RIGHT);
            hi.add(sameSideAlignRight);
            
            CheckBox sameSideTooLong = new CheckBox("Too Long to fit on one line.  Lorem Ipsum, hello world, fooobarlllll  hello again");
            sameSideTooLong.setOppositeSide(false);
            hi.add(sameSideTooLong);
            
            int[] alignments = new int[]{LEFT, CENTER, RIGHT};
            int[] textPositions = new int[]{LEFT, RIGHT, TOP, BOTTOM};
            boolean[] opposites = new boolean[]{true, false};
            for (int align : alignments) {

                for (boolean opp : opposites) {
                    CheckBox cb = new CheckBox(tr("Align")+str(align)+"/opp="+opp);
                    //cb.setTextPosition(textPos);
                    $(cb).selectAllStyles().setAlignment(align);
                    cb.setOppositeSide(opp);
                    hi.add(cb);
                }
                
            }
            
            for (int align : alignments) {

                //for (boolean opp : opposites) {
                    Label cb = new Label(tr("Align")+str(align));
                    //cb.setTextPosition(textPos);
                    $(cb).selectAllStyles().setAlignment(align);
                    //cb.setOppositeSide(opp);
                    hi.add(cb);
                //}
                
            }
            
            for (int align : alignments) {

                //for (boolean opp : opposites) {
                    Label cb = new Label(tr("Align")+str(align) + " Too Long to fit on one line.  Lorem Ipsum, hello world, fooobarlllll  hello again");
                    //cb.setTextPosition(textPos);
                    $(cb).selectAllStyles().setAlignment(align);
                    //cb.setOppositeSide(opp);
                    hi.add(cb);
                //}
                
            }
            
            for (int align : alignments) {

                for (boolean opp : opposites) {
                    CheckBox cb = new CheckBox(tr("Align")+str(align)+"/opp="+opp+ " Too Long to fit on one line.  Lorem Ipsum, hello world, fooobarlllll  hello again");
                    //cb.setTextPosition(textPos);
                    $(cb).selectAllStyles().setAlignment(align);
                    cb.setOppositeSide(opp);
                    hi.add(cb);
                }
                
            }
            
            FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_FIBER_MANUAL_RECORD, new Label().getStyle());
            for (int align : alignments) {

                //for (boolean opp : opposites) {
                for (int textPos : textPositions) {
                    Label cb = new Label(tr("Align")+str(align)+"/pos="+str(textPos));
                    cb.setTextPosition(textPos);
                    $(cb).selectAllStyles().setAlignment(align);
                    cb.setIcon(icon);
                    //cb.setOppositeSide(opp);
                    hi.add(cb);
                }
                
            }
            for (int align : alignments) {

                //for (boolean opp : opposites) {
                for (int textPos : textPositions) {
                    hi.add(new Label(tr("Align")+str(align)+"/pos="+str(textPos)+":"));
                    Label cb = new Label(tr("Align")+str(align)+"/pos="+str(textPos) + " Too Long to fit on one line.  Lorem Ipsum, hello world, fooobarlllll  hello again");
                    cb.setTextPosition(textPos);
                    $(cb).selectAllStyles().setAlignment(align);
                    cb.setIcon(icon);
                    //cb.setOppositeSide(opp);
                    hi.add(cb);
                }
                
            }
            
            for (int align : alignments) {

                //for (boolean opp : opposites) {
                for (int textPos : textPositions) {
                    hi.add(new Label("Ticker:"+tr("Align")+str(align)+"/pos="+str(textPos)+":"));
                    Label cb = new Label(tr("Align")+str(align)+"/pos="+str(textPos) + " Too Long to fit on one line.  Lorem Ipsum, hello world, fooobarlllll  hello again");
                    
                    cb.setTextPosition(textPos);
                    $(cb).selectAllStyles().setAlignment(align);
                    cb.setIcon(icon);
                    //cb.setOppositeSide(opp);
                    hi.add(cb);
                    cb.startTicker();
                }
                
            }
            
            for (int align : alignments) {
                FlowLayout fl = new FlowLayout();
                fl.setAlign(align);
                Container cnt = new Container(fl);
                $(cnt).selectAllStyles()
                        .setBorder(Border.createLineBorder(1))
                        .setPaddingMillimeters(0, 2, 2, 2);
                Label l = new Label();
                $(l).selectAllStyles().setPadding(0).setMargin(0);
                cnt.add(l);
                hi.add(FlowLayout.encloseCenter(cnt));
                l.setText(str(align));
                
                
            }
            
            $("*", this).selectAllStyles().setFont(arialbd);
            
        }
    
    }

    private static boolean hebrew=false;
    
    private static String tr(String str) {
        if (!hebrew) {
            return str;
        }
        if ("Align".equals(str)) {
            return "יישר קו";
        }
        if ("Left".equals(str)) {
            return "שמאלה";
        }
        if ("Right".equals(str)) {
            return "ימין";
        }
        if ("Center".equals(str)) {
            return "מרכז";
        }
        if ("Top".equals(str)) {
            return "חלק עליון";
        }
        if ("Bottom".equals(str)) {
            return "בתחתית";
        }
        
        return str;
        
    }
    
    private static String str(int align) {
        switch (align) {
            case LEFT:
                return tr("Left");
            case RIGHT:
                return tr("Right");
            case Component.CENTER:
                return tr("Center");
            case Component.TOP:
                return tr("Top");
            case Component.BOTTOM:
                return tr("Bottom");
            default:
                return String.valueOf(align);
        }
    }

    public void stop() {
        current = getCurrentForm();
        if(current instanceof Dialog) {
            ((Dialog)current).dispose();
            current = getCurrentForm();
            
        }
    }
    
    public void destroy() {
    }

}
